//
//  YQPlaceholderTextView.m
//  GCLibrary
//
//  Created by Guillaume Campagna on 10-11-16.
//  Copyright 2010 LittleKiwi. All rights reserved.
//

#import "YQPlaceholderTextView.h"

@interface YQPlaceholderTextView ()

@property (nonatomic, strong) UILabel *placeholderLabel;

@end

@implementation YQPlaceholderTextView

#pragma mark -
#pragma mark Initialisation

- (id) initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updatePlaceholderLabel) name:UITextViewTextDidChangeNotification object:self];
        self.placeholderColor = [UIColor lightGrayColor];
    }
    return self;
}

- (void) setFont:(UIFont *)font
{
    [super setFont:font];
    self.placeholderLabel.font = font;
}

- (void) setPlaceholderColor:(UIColor *)placeholderColor
{
    _placeholderColor = placeholderColor;
    self.placeholderLabel.textColor = placeholderColor;
}

- (void) setPlaceholder:(NSString *)placeholder
{
    self.placeholderLabel.text = placeholder;
    [self updatePlaceholderLabel];
}

- (NSString *) placeholder
{
    return self.placeholderLabel.text;
}

- (UILabel *)placeholderLabel
{
    if (_placeholderLabel) {
        return _placeholderLabel;
    }
    
    _placeholderLabel = [[UILabel alloc] init];
    _placeholderLabel.numberOfLines = 0;
    _placeholderLabel.userInteractionEnabled = NO;
    [self updatePlaceholderLabel];
    return _placeholderLabel;
}

- (void) layoutSubviews
{
    [super layoutSubviews];
    [self updatePlaceholderLabel];
}

#pragma mark - Update

- (void)updatePlaceholderLabel
{
    if (self.text.length) {
        [self.placeholderLabel removeFromSuperview];
        return;
    }
    
    [self insertSubview:self.placeholderLabel atIndex:0];
    
    self.placeholderLabel.textAlignment = self.textAlignment;
    
    CGFloat lineFragmentPadding = self.textContainer.lineFragmentPadding;
    UIEdgeInsets textContainerInset = self.textContainerInset;
    CGFloat x = lineFragmentPadding + textContainerInset.left;
    CGFloat y = textContainerInset.top;
    CGFloat width = CGRectGetWidth(self.bounds) - x - lineFragmentPadding - textContainerInset.right;
    CGFloat height = [self.placeholderLabel sizeThatFits:CGSizeMake(width, 0)].height + 1;
    self.placeholderLabel.frame = CGRectMake(x, y, width, height);
}

#pragma mark -
#pragma mark Dealloc

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

@end
